package com.rentapark.app;

import java.io.IOException;
import java.util.List;
import java.util.Locale;





import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;



import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;


import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import android.os.Handler;

//this is a map activity for the user to choose a parkingspot within the map
public class SearchAddress extends MapActivity{
	MapView view;
	List<Overlay> overlays;
	MapController control;
	MyLocationOverlay myLocation;
	int LONG_PRESS_TIME =500;
	LocationManager manager;
	GeoPoint currentPoint;
	GeoPoint myLoc;
	String towers;
	int lat=0;
	int longi=0;
	private EditText addressToSearch;
	GeoPoint touchedPoint;
	int x;
	int y;
	long startP;
	long stopP;
	Handler mHandler= new Handler();

	@Override

	public void onCreate(Bundle savedInstanceState){   
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_address);

		view = (MapView) findViewById(R.id.themap);
		overlays= view.getOverlays();

		view.setBuiltInZoomControls(true);
		view.setClickable(true);
		view.setLongClickable(true);
		control= view.getController();
		
		Touch t = new Touch();
		overlays.add(t);

		//gps definitions for showing in the map the user's location
		manager= (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		Criteria crit =new Criteria(); //get best deafult critiria (GPS/cellular/Wi-Fi)
		towers= manager.getBestProvider(crit, false); //best reception/power re/ things like that
		myLocation= new MyLocationOverlay(SearchAddress.this, view);	//enable my location
		myLocation.enableMyLocation();
		overlays.add(myLocation);	//display user's location in the map
		
		Location loc = manager.getLastKnownLocation(towers);	//get your location
		if(loc!=null)
		{
			lat=(int)(loc.getLatitude()*1E6);
			longi =(int)(loc.getLongitude()*1E6);
		}

		myLoc=new GeoPoint(lat, longi);
		currentPoint= myLoc;
		control.animateTo(myLoc);
		control.setZoom(16);
		view.invalidate();

		//this button is used when the user wants to center the map on its present location
		ImageButton currLoc=  (ImageButton) findViewById(R.id.myLoc);
		currLoc.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				//get myLocation
				Location loc = manager.getLastKnownLocation(towers);
				if(loc!=null)
				{
					lat=(int)(loc.getLatitude()*1E6);
					longi =(int)(loc.getLongitude()*1E6);
				}
				myLoc=new GeoPoint(lat, longi);	
				currentPoint= myLoc;
				control.animateTo(myLoc);
				control.setZoom(16);
			}
		});

		addressToSearch= (EditText) findViewById(R.id.searchAddrET);
		ImageButton searchAd=  (ImageButton) findViewById(R.id.searchAdd);
		searchAd.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				GeoPoint p= getForwardGeoCoder();
				currentPoint=p;
				control.animateTo(p);
				control.setZoom(15);
				Toast toast = Toast.makeText(SearchAddress.this, "Latitude is " + p.getLatitudeE6() + " " + "Longitude is " + p.getLongitudeE6(), Toast.LENGTH_LONG);
				toast.show();
			}
		});
	}


//this method is used when the user makes a long touch on the map- it means that a parking spot was selected
	private final Runnable mTask = new Runnable() {
		@Override
		public void run() {
			//long press -- set new place on map!!
			Log.d("MyApp", "Long press!");
			Geocoder geoCoder= new Geocoder(getBaseContext(),Locale.getDefault());
			String 	disply ="";
			//insert the touched point address into disply
			Log.d("touched place",Double.toString(touchedPoint.getLatitudeE6()));

			//dialog asking the user to confirm the parking spot location
			final AlertDialog alertMsg = new AlertDialog.Builder(SearchAddress.this).create();
			alertMsg.setTitle("Is your parking spot in the place you tapped?");
			alertMsg.setMessage(disply);
			alertMsg.setButton2("No", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					//					AddAllPins(some);
				}
			});

			alertMsg.setButton("Yes", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					SharedPreferences ref = getSharedPreferences("com.ruthy.parkApp",MODE_PRIVATE);
					SharedPreferences.Editor ed = ref.edit();
					//save location chosen by the user
					ed.putString("parking_offer", "true");
					ed.putString("touchedLatitud", Integer.toString(touchedPoint.getLatitudeE6()));
					ed.putString("touchedLongitud", Integer.toString(touchedPoint.getLongitudeE6()));
					Log.d("searchAddress-lati",Integer.toString(touchedPoint.getLatitudeE6()));
					Log.d("searchAddress-longi",Integer.toString(touchedPoint.getLongitudeE6()));
					ed.commit();
					finish();
				}
			});
			alertMsg.show();
		}
	};


	class Touch extends Overlay{
		//method handling onTouch event
		public boolean onTouchEvent(MotionEvent e, MapView mv){
			if(e.getAction() ==MotionEvent.ACTION_DOWN)
			{
				startP = e.getEventTime();
				x=(int)e.getX();
				y=(int)e.getY();
				touchedPoint= view.getProjection().fromPixels(x,y); 
				mHandler.postDelayed(mTask, LONG_PRESS_TIME);
			}else if(e.getAction() == MotionEvent.ACTION_UP){
				stopP =e.getEventTime();
				if(stopP-startP <LONG_PRESS_TIME)
					mHandler.removeCallbacks(mTask);
			}
			return false;

		}
	}

//this method receives an address and returns a geopoint
	protected GeoPoint getForwardGeoCoder (){
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(addressToSearch.getWindowToken(), 0);
		Geocoder geoCoder= new Geocoder(getBaseContext(),Locale.getDefault());
		GeoPoint pointToReturn =myLoc;
		try
		{
			List<Address> address= geoCoder.getFromLocationName(addressToSearch.getText().toString(), 8);
			if(address.size()>0)			
				pointToReturn =new GeoPoint((int)((address.get(0).getLatitude())*1E6), (int)((address.get(0).getLongitude())*1e6));

		} catch (IOException ex) {
			ex.printStackTrace();
		}	
		return pointToReturn;
	}
	//this method receives a geopoint and returns an address as a string
	protected String getReverseGeoCoder (GeoPoint point){
		Geocoder geoCoder= new Geocoder(getBaseContext(),Locale.getDefault());
		String 	display ="";
		try
		{
			List<Address> address =geoCoder.getFromLocation(point.getLatitudeE6()/1E6, point.getLongitudeE6()/1E6, 1);
			if(address.size()>0)
			{

				for(int i=0;i<address.get(0).getMaxAddressLineIndex();i++)
				{		
					display += address.get(0).getAddressLine(i)+ "\n";
				}
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return display;
	}
	//overrided method for gps use
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}


}
